﻿using System;
using System.ComponentModel;
using Loki;
using Loki.UI;
using Loki.UI.Win;
using Luna.UI.Project;

namespace Luna.UI.Win.Project
{
    /// <summary>
    /// Project category list view.
    /// </summary>
    public partial class ProjectListView : LunaView, IView<ProjectListViewModel>
    {
        public ProjectListView()
        {
            InitializeComponent();
            this.BindingChanged += new EventHandler(ProjectListView_BindingChanged);
        }

        private void ProjectListView_BindingChanged(object P_Sender, EventArgs e)
        {
            COL_Name.Bind<DisplayableProject>(x => x.Name);
            COL_Description.Bind<DisplayableProject>(x => x.Description);
            COL_TotalAllocated.Bind<DisplayableProject>(x => x.AllocatedAmount, EDT_Amount);
            COL_TotalIncome.Bind<DisplayableProject>(x => x.IncomeAmount, EDT_Amount);
            COL_TotalOutcome.Bind<DisplayableProject>(x => x.OutcomeAmount, EDT_Amount);

            VIEW_Projects.Configure(ViewModel.Projects);
            VIEW_Projects.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(VIEW_Projects_FocusedRowChanged);
            this.WatchChange(ViewModel, v => v.SelectedProjectIndex, v => v.ViewModel_SelectedProjectIndex_Changed);
        }

        private void ViewModel_SelectedProjectIndex_Changed(object P_Sender, PropertyChangedEventArgs e)
        {
            VIEW_Projects.FocusedRowHandle = (int)ConverterHelper.HandleToIndex.Convert(ViewModel.SelectedProjectIndex, typeof(int), VIEW_Projects, UIContext.Culture);
        }

        private void VIEW_Projects_FocusedRowChanged(object P_Sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            ViewModel.SelectedProjectIndex = (int)ConverterHelper.HandleToIndex.ConvertBack(VIEW_Projects.FocusedRowHandle, typeof(int), VIEW_Projects, UIContext.Culture);
        }

        public new ProjectListViewModel ViewModel
        {
            get { return (ProjectListViewModel)base.ViewModel; }
            set { base.ViewModel = value; }
        }

        private void BAI_Add_ItemClick(object P_Sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ViewModel.Add.Execute(null);
        }

        private void VIEW_Projects_DoubleClick(object P_Sender, EventArgs e)
        {
            if (VIEW_Projects.IsValidRowHandle(VIEW_Projects.FocusedRowHandle))
            {
                ViewModel.Open.Execute(null);
            }
        }
    }
}